package com.example.fresh_market.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.android.volley.Request;
import com.example.fresh_market.databinding.ActivityCategoryEditBinding;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.CateReq;
import com.example.fresh_market.request.ProdCateResp;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;

public class CategoryEditActivity extends AppCompatActivity {

    private ActivityCategoryEditBinding binding;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCategoryEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mContext = this;
        Gson gson = new Gson();
        String json = getIntent().getStringExtra("cate");
        if (StringUtils.isNotBlank(json)) {
            ProdCateResp prodCateResp = gson.fromJson(json, ProdCateResp.class);
            binding.editId.setText(prodCateResp.getId());
            binding.editCateName.setText(prodCateResp.getCateName());
            binding.editCateDescription.setText(prodCateResp.getDescription());
        }
        binding.cateSubmit.setOnClickListener(v -> {
            String cateId = binding.editId.getText().toString();
            boolean blank = StringUtils.isBlank(cateId);
            int method = blank ? Request.Method.POST : Request.Method.PUT;
            CateReq cateReq = CateReq.builder()
                    .cateName(binding.editCateName.getText().toString())
                    .description(binding.editCateDescription.getText().toString())
                    .build();
            if (!blank) {
                cateReq.setId(binding.editId.getText().toString());
            }
            saveOrUpdateProduct(method, cateReq);
        });
    }

    private void saveOrUpdateProduct(int method, CateReq cateReq) {
        Gson gson = new Gson();
        HttpUtil.sendJsonRequest(mContext, method, "/admin/product/cate", gson.toJson(cateReq), response -> {
            ApiResponse apiResponse = gson.fromJson(response.toString(), ApiResponse.class);
            if (apiResponse.getCode() == 200) {
                ToastUtil.showToast(mContext, "保存成功");
                finish();
            }
        });
    }
}
